<template>
  <page-layout>
    <a-spin :spinning="isLoading">
      <a-card>
        <footer-button :buttons="state.buttons" />
        <a-form>
          <a-row type="flex" justify="space-between">
            <a-col
              :span="7"
              v-for="item in baseFields.fields"
              :key="item.field"
            >
              <a-form-item :label="item.title" class="mb-5">
                {{ handleFormEmptyData(baseFields.data[item.field]) }}
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <a-tabs :active-key(v-model)="activeKey" size="small">
          <a-tab-pane key="detail" :tab="t('button.detail')">
            <DetailBaseForm :data="baseFields.data" />
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </a-spin>
    <a-modal
      :visible="state.modalVisible"
      v-if="state.modalVisible"
      :title="t('button.generateQrCode')"
      :cancelText="t('button.cancel')"
      :okText="t('button.downloadQrCode')"
      @ok="handleOk"
      @cancel="cancel">
      <div class="qrcode" id="qrcode">
        <qrcode-vue :value="state.qrCodeUrl" :size="200" level="H" />
      </div>
    </a-modal>
  </page-layout>
</template>
<script>
export default {
  name: "activity-management-detail"
}
</script>
<script setup>
import { reactive, onActivated, createVNode, ref } from "vue";
import { message, modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { useRoute, useRouter } from "vue-router";
import { handleFormEmptyData } from "@/tools/filters";
import { getDictByCodesReturnObj } from "@/tools/get-dict";
import dictEnum from "@/const/dict";
import { isEmpty } from "@/tools/common";
import DetailBaseForm from "./components/detail-base-form";
import { details, update } from "@/api/module/activity-management";
import moment from "moment";
import QrcodeVue from 'qrcode.vue'
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const isLoading = ref(false);
const state = reactive({
  modalVisible: false,
  qrCodeUrl: "https://crmh5.lightcourse.com/#/bindasbusiness",
  buttons: [
    {
      name: "downloadQrCode",
      event: () => handleQrCode(),
      type: "primary",
      code: "",
    },
    {
      name: "applyForPayment",
      event: () => handlePay(),
      type: "primary",
      code: "",
    },
    {
      name: "adjust",
      event: () => handleAdjust(),
      type: "primary",
      code: "",
    },
    {
      name: "earlyEnd",
      event: () => handleEnd(),
      type: "primary",
      code: "",
    },
  ],
  commisType: 0,
});

const handleQrCode = () => {
  state.modalVisible = true
};
const handleOk = () => {
  let canvas = document.getElementById('qrcode').getElementsByTagName('canvas')
  let a = document.createElement('a')
  a.href = canvas[0].toDataURL('image/png')
  a.download = baseFields.data.actName
  a.click()
  cancel()
}
const cancel = () => {
  state.modalVisible = false
}
const handlePay = () => {};
const handleAdjust = () => {};
const handleEnd = () => {
  if (baseFields.data.id) {
    if (baseFields.data.actStatus == t('activityManage.label.active-13')) {
      return message.warning(t('activityManage.label.active-14'))
    }
    modal.confirm({
      title: `${t('activityManage.label.active-15')}?`,
      icon: createVNode(ExclamationCircleOutlined),
      okText: t('button.determine'),
      cancelText: t('button.cancel'),
      onOk() {
        update({ id: baseFields.data.id, actStatus: 2 })
          .then((res) => {
            if (res.success) {
              message.success({ content: t('message.operationSucceeded'), duration: 1 }).then(() => {
                router.push({
                  path: "/market/activity-management",
                });
              });
            } else {
              message.warning({ content: t('message.operationFailed'), duration: 1 });
            }
          })
          .catch((err) => {
            console.log("err: ", err);
            message.warning({ content: t('message.operationFailed'), duration: 1 });
          });
      },
    });
  }
};

const baseFields = reactive({
  fields: [
    { title: t('activityManage.label.activityName'), field: "actName" },
    { title: t('activityManage.label.active-12'), field: "actTimes" },
    { title: t('activityManage.label.state'), field: "actStatus" },
    { title: t('activityManage.label.personInCharge'), field: "actHead" },
    { title: t('activityManage.label.saleHead'), field: "saleHead" },
    { title: t('label.creator'), field: "createBy" },
    { title: t('label.creationTime'), field: "createTime" },
  ],
  data: {},
  dict: {},
});
const getDataByDict = (data, dictKey) => {
  if (isEmpty(data)) return "-";
  const item = baseFields.dict[dictKey].find((v) => v.value == data);
  if (isEmpty(item)) return "-";
  return item.label;
};

onActivated(async () => {
  const result = route.query;
  if (!result || !result.id) return;
  baseFields.dict = await getDictByCodesReturnObj([
    dictEnum.ACT_TYPE,
    dictEnum.ACT_STATUS,
    dictEnum.YES_OR_NO,
    dictEnum.DRA_DES,
    dictEnum.CONTRACT_STATUS,
  ]);

  isLoading.value = true;
  let res = await details({ id: result.id });
  if (res.code === 500) return message.error(t('label.failedToGetDetails'));
  let times = res.data.beginTime
    ? moment(res.data.beginTime).format("YYYY-MM-DD HH:mm:ss")
    : "";
  times =
    times + "~" + res.data.endTime
      ? moment(res.data.endTime).format("YYYY-MM-DD HH:mm:ss")
      : "";
  res.data.actTimes = times;
  res.data.actType = getDataByDict(res.data.actType, dictEnum.ACT_TYPE);
  res.data.actStatus = getDataByDict(res.data.actStatus, dictEnum.ACT_STATUS);
  res.data.isSetmoney = getDataByDict(res.data.isSetmoney, dictEnum.ACT_STATUS);
  res.data.ylBurn = getDataByDict(res.data.ylBurn, dictEnum.DRA_DES);
  // res.data.contractDetails = [{
  //   demand: '要求多多',
  //   contractStatus: '1',
  //   remark: '发带伞发送到发斯蒂芬发带伞发送到发斯蒂芬发蒂芬发带伞发送到发斯蒂芬发蒂芬发带伞发送到发斯蒂芬发带伞发送到发斯蒂芬发带伞发送到发斯蒂芬发带伞发送到发斯蒂芬发带伞发送到发斯蒂芬',
  //   tagPeople: '张三',
  //   tagTime: '2021-09-28 18:26:00',
  // }]
  res.data.contractDetails.map((item) => {
    item.showBtn = true;
    item.contractStatus = getDataByDict(
      item.contractStatus,
      dictEnum.CONTRACT_STATUS
    );
    return item;
  });
  baseFields.data = res.data;
  isLoading.value = false;
});
</script>

<style lang="scss" scoped>
.qrcode {
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>